/*
 * 工具函数统一出口
 */
import {
  EMPLOYEE_TOKEN,
  EMPLOYEE_ID,
  EMPLOYEE_DEPT_ID,
  EMPLOYEE_PRIVATE_DEPT_ID,
  EMPLOYEE_PUBLIC_DEPT_ID,
  EMPLOYEE_DEPT_NAME,
  EMPLOYEE_BRANCH_ID,
  EMPLOYEE_BRANCH_NAME,
  DEVICE_ID,
  EMPLOYEE_ROLE,
  DOMAIN_TYPE,
  EMPLOYEE_NUM_REG,
  NUMBER_REG,
  ADMIN_FIELD_TYPE,
  CURRENT_FIELD
} from './enums/index'
import { map, toNumber, divide } from 'lodash-es'
import Cookie from 'js-cookie'

/**
 * 添加cookie
 * @param {string} name<必须>  // cookie名
 * @param {string} value<必须>  // cookie值
 * @param {number} expiresHours<必须>  // 过期时间
 **/
export const addCookie = (name, value, expiresHours) => {
  let cookieString = name + '=' + escape(value) + '; path=/'
  // 判断是否设置过期时间
  if (expiresHours > 0) {
    const date = new Date()
    date.setTime(date.getTime + expiresHours * 3600 * 1000)
    cookieString = cookieString + '; expires=' + date.toUTCString()
  }
  document.cookie = cookieString
}

/**
 * 获取cookie
 * @param {string} name<必须>  // cookie名
 **/
export const getCookie = name => {
  const strCookie = document.cookie
  const arrCookie = strCookie.split(';')
  for (let i = 0; i < arrCookie.length; i++) {
    const arr = arrCookie[i].split('=')
    if (arr[0] === name) return unescape(arr[1])
  }
  return ''
}

/**
 * 删除cookie
 * @param {string} name<必须>  // cookie名
 **/
export const deleteCookie = name => {
  const date = new Date()
  date.setTime(date.getTime() - 10000)
  document.cookie = name + '=; path=/; expires=' + date.toUTCString()
}

/**
 * 事件绑定方法
 * @param {object} element<必须>  // dom对象
 * @param {string} type<必须>  // 事件类型
 * @param {function} handler<必须>  // 触发事件后的回调函数
 **/
export const bindEvent = (element, type, func) => {
  if (element.addEventListener) {
    element.addEventListener(type, func, false)
  } else if (element.attachEvent) {
    element.attachEvent('on' + type, func)
  } else {
    element['on' + type] = func
  }
}

/**
 * 移除事件绑定
 * @param {object} element<必须>  // dom对象
 * @param {string} type<必须>  // 事件类型
 * @param {function} handler<必须>  // 触发事件后的回调函数
 **/
export const removeEvent = (element, type, handler) => {
  if (element.removeEventListener) {
    element.removeEventListener(type, handler, false)
  } else if (element.detachEvent) {
    element.detachEvent('on' + type, handler)
  } else {
    element['on' + type] = null
  }
}

/**
 * 深拷贝
 * @param {object} obj<必须>  // 被拷贝的对象
 * @returns {object} c // 拷贝后返回的对象
 **/
export const deepCopy = obj => {
  if (typeof obj !== 'object' || obj === null) return obj
  const clone = Array.isArray(obj) ? [] : {}
  for (const i in obj) {
    if (typeof obj[i] === 'object') {
      clone[i] = deepCopy(obj[i])
    } else {
      clone[i] = obj[i]
    }
  }
  return clone
}

/**
 * 设置localStorage
 * @param {string} name<必须>  // localStorage名
 * @param {string} value<必须>  // localStorage值
 **/
export const setLocalStorage = (name, value) => {
  localStorage.setItem(name, value)
}

/**
 * 获取localStorage
 * @param {string} name<必须>  // localStorage名
 * @returns
 **/
export const getLocalStorage = name => {
  return localStorage.getItem(name)
}

/**
 * 删除localStorage
 * @param {string} name
 */
export const removeLocalStorage = name => {
  localStorage.removeItem(name)
}

/**
 * 设置sessionStorage
 * @param {string} name<必须>  // localStorage名
 * @param {string} value<必须>  // localStorage值
 **/
export const setSessionStorage = (name, value) => {
  sessionStorage.setItem(name, value)
}

/**
 * 获取sessionStorage
 * @param {string} name<必须>  // localStorage名
 * @returns
 **/
export const getSessionStorage = name => {
  return sessionStorage.getItem(name)
}

export const getCorpCookie = name => {
  // const appId = sessionStorage.getItem('appId')
  return Cookie.get(`${getLocalStorage('corpId')}-${name}`)
  // const strCookie = document.cookie
  // const arrCookie = strCookie.split('; ')
  // for (let i = 0; i < arrCookie.length; i++) {
  //   const arr = arrCookie[i].split('=')
  //   if (`${appId}-${name}` === arr[0]) {
  //     return decodeURIComponent(arr[1])
  //   }
  // }
  // return null
}

export const setCorpCookie = (name, value) => {
  // const appId = sessionStorage.getItem('appId')
  Cookie.set(`${getLocalStorage('corpId')}-${name}`, value)
}

/**
 * 格式化日期
 * @param {object} date<必须>  // 日期，可以是各种有效的日期，包括字符串、日期对象、时间戳
 * @param {string} fmt<可选>  // 需要的格式
 * @returns {string} fmt // 返回格式化后的日期
 **/
export const formatDate = (date, fmt) => {
  if (!date) {
    return date
  } else {
    if (!fmt) {
      fmt = 'YYYY-MM-DD hh:mm:ss'
    }

    const isString = typeof date === 'string'
    const isFloatNUmber = /^[0-9]+.?[0-9]*/.test(date)
    const isHasSeparator = /[-:/]/.test(date)
    const time =
      isString && isFloatNUmber && !isHasSeparator
        ? new Date(parseFloat(date))
        : new Date(date)

    const o = {
      'M+': time.getMonth() + 1, // 月份
      'D+': time.getDate(), // 日
      'h+': time.getHours(), // 小时
      'm+': time.getMinutes(), // 分
      's+': time.getSeconds(), // 秒
      'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
      S: time.getMilliseconds() // 毫秒
    }
    if (/(Y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (time.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }

    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
    return fmt
  }
}

/**
 * 数组转成 Map
 * @param {Array} {value: '', text: ''}[] <必须>
 * @returns {Map}
 **/
export function arrayToMap(array) {
  const constantMap = new Map()
  array.forEach(item => {
    constantMap.set(item.value, item.text)
  })
  return constantMap
}

/**
 * 获取员工ID
 * @param {object}
 * @returns {object}
 **/
export const readEmployee = () => {
  const deviceId = getLocalStorage(DEVICE_ID) || process.env.VUE_APP_DEVICE_ID
  const employeeId =
    getLocalStorage(EMPLOYEE_ID) || process.env.VUE_APP_EMPLOYEE_ID

  const departmentId =
    getLocalStorage(EMPLOYEE_DEPT_ID) || process.env.VUE_APP_EMPLOYEE_DEPT_ID
  const departmentName =
    getLocalStorage(EMPLOYEE_DEPT_NAME) ||
    process.env.VUE_APP_EMPLOYEE_DEPT_NAME

  const branchId =
    getSessionStorage(EMPLOYEE_BRANCH_ID) ||
    getLocalStorage(EMPLOYEE_BRANCH_ID) ||
    process.env.VUE_APP_EMPLOYEE_BRANCH_ID
  const branchName =
    getSessionStorage(EMPLOYEE_BRANCH_NAME) ||
    getLocalStorage(EMPLOYEE_BRANCH_NAME) ||
    process.env.VUE_APP_EMPLOYEE_BRANCH_NAME

  const domainType =
    getLocalStorage(DOMAIN_TYPE) || process.env.VUE_APP_DOMAIN_TYPE

  // 对私员工部门
  const priDeptId =
    getLocalStorage(EMPLOYEE_PRIVATE_DEPT_ID) ||
    process.env.VUE_APP_EMPLOYEE_PRIVATE_DEPT_ID

  // 对公员工部门
  const pubDeptId =
    getLocalStorage(EMPLOYEE_PUBLIC_DEPT_ID) ||
    process.env.VUE_APP_EMPLOYEE_PUBLIC_DEPT_ID

  // 应用类型
  const fieldType =
    getLocalStorage(ADMIN_FIELD_TYPE) || process.env.VUE_APP_FIELD_TYPE

  if (process.env.NODE_ENV === 'development') {
    setLocalStorage(EMPLOYEE_ID, employeeId)
    setLocalStorage(EMPLOYEE_DEPT_ID, departmentId)
    setLocalStorage(EMPLOYEE_PRIVATE_DEPT_ID, priDeptId) // 对私员工部门
    setLocalStorage(EMPLOYEE_PUBLIC_DEPT_ID, pubDeptId) // 对公员工部门
    setLocalStorage(EMPLOYEE_DEPT_NAME, departmentName)
    setLocalStorage(EMPLOYEE_BRANCH_ID, branchId)
    setLocalStorage(EMPLOYEE_BRANCH_NAME, branchName)
    setLocalStorage(DEVICE_ID, deviceId)
    setLocalStorage(EMPLOYEE_ROLE, '1')
    setLocalStorage(DOMAIN_TYPE, domainType) // PERSONAL BUSINESS
    setLocalStorage(ADMIN_FIELD_TYPE, fieldType) // QWEJ HQJLY
    setLocalStorage(CURRENT_FIELD, process.env.VUE_APP_CURRENT_FIELD)
  }

  return {
    departmentName,
    departmentId,
    employeeId,
    branchName,
    fieldType,
    branchId
  }
}

// 获取对私对公员工部门Id
export const getPriDeptId = () => getLocalStorage(EMPLOYEE_PRIVATE_DEPT_ID)
export const getPubDeptId = () => getLocalStorage(EMPLOYEE_PUBLIC_DEPT_ID)

/**
 * 获取员工token
 * @param {object}
 * @returns {object}
 **/
export const readeEmployeeToken = () => {
  let token = ''
  console.log('process.env.NODE_ENV:', process.env.NODE_ENV)
  console.log('getLocalStorage(EMPLOYEE_TOKEN):', getLocalStorage(EMPLOYEE_TOKEN))
  if (process.env.NODE_ENV === 'development') {
    token =
      getLocalStorage(EMPLOYEE_TOKEN) ||
      process.env.VUE_APP_EMPLOYEE_TOKEN
  } else {
    token = getLocalStorage(EMPLOYEE_TOKEN)
  }
  return token
}

/**
 *
 * @param {String} storageKey localStorage的Key
 * @param {Function} callBack 回调执行函数
 */
export const afterStorageDataExec = (externalUserid, callBack) => {
  let testCount = 0
  const maxTest = 150
  const time = 200

  const exec = () => {
    if (getSessionExternalUserId() || externalUserid) {
      callBack()
    } else {
      if (testCount < maxTest) {
        testCount++
        setTimeout(exec, time)
      } else {
        console.log('afterStorageDataExec尝试超过30秒无法获取信息')
      }
    }
  }

  exec()
}

export const setSessionExternalUserId = value => {
  sessionStorage.setItem('EXTERNAL_USER_ID', value)
}

export const getSessionExternalUserId = () => {
  // return 'wmImf5EQAA18Y2FOTCx8g_id5RzkPZHw'
  return sessionStorage.getItem('EXTERNAL_USER_ID')
}

/**
 * @description 对象转换成URL参数
 * @param {*} paramsObj
 * @returns
 */
export const formatObjToParams = paramsObj => {
  const data = []
  map(paramsObj, (value, key) => {
    data.push(`${key}=${value}`)
  })
  return data.join('&')
}

export const isDevelopment = () => {
  return process.env.NODE_ENV === 'development'
}

/**
 * @description 转换图片、视频、pdf等文件的src
 * @param {*} fileUrlKey
 * @returns
 */
export const formatFileSrc = fileUrlKey => {
  return (
    window.location.origin +
    `/api/fin-scrm-adapt/file/downloadFile?key=${fileUrlKey}`
  )
}

/**
 * 处理使用axios导出的返回数据
 * @param data 返回的Blob类型的数据
 * @param contentDisposition 相应头中content-disposition
 */
export const handleExportResponse = (data, contentDisposition) => {
  // console.log('1111', contentDisposition)
  const blob = new Blob([data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  })

  // 获取headers中的filename文件名
  let tempName
  if (contentDisposition.indexOf(';') > -1) {
    tempName = contentDisposition.split(';')[1].split('filename=')[1]
  } else {
    tempName = contentDisposition.split('filename=')[1]
  }
  // // iso8859-1的字符转换成中文
  // fileName = decodeURI(escape(fileName))
  // // 去掉双引号
  // fileName = fileName.replace(/\"/g, '')
  // 解决中文乱码
  const fileName = decodeURI(tempName)

  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob) // 创建下载的链接
  downloadElement.href = href
  downloadElement.download = fileName // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

export const timeFormat = {
  dateMinute: 'YYYY-MM-DD HH:mm',
  dataByBias: 'YYYY/M/D'
}

/**
 * 手机号校验
 * 1. pl2、vt 不使用正规校验
 * 2. 生产使用正规校验
 * @type {RegExp}
 */
export const PHONE_REG = (() => {
  if (!window.projectConf.useSpecialPhoneReg) {
    return /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
  }
  return /^1\d{10}$/
})()

export const checkMobile = val => {
  // 校验手机号的正则
  const phoneReg = PHONE_REG
  return phoneReg.test(val)
}

// 临时获取渠道活码，扫码的unionId方法，仅供在无法获取unionId时使用，生产环境需要在调用的地方注释掉
export const getChannelUnionid = () => {
  if (process.env.NODE_ENV === 'development') {
    return 'wmImf5EQAAkTtX4u1Ujv8Qw7mx5b9DGw'
  }

  let unionIdIndex = window.projectConf.currUnionId
  if (unionIdIndex < 0) {
    unionIdIndex = Math.floor(
      Math.random() * window.projectConf.unionIds.length
    )
  }
  return window.projectConf.unionIds[unionIdIndex]
}

/**
 * 函数组合
 * @param fns 函数集合
 */
export const compose =
  (...fns) =>
    (...args) =>
      fns.reduceRight((val, fn) => fn.apply(null, [].concat(val)), args)

/**
 * 添加千分位符
 * @param str
 * @return {string|*}
 */
export function toLocaleString(str) {
  return str ? toNumber(str).toLocaleString() : str
}
/**
 * 万为单位添加千分位符
 * @param str
 * @return {string|*}
 */
export function toLocaleStringWithTenThousand(str) {
  if (!str) {
    return str
  }
  if (isNaN(str)) {
    return '-'
  }
  const division = val => divide(val, 10000)
  const fn = compose(toLocaleString, division)
  return fn(str)
}

/**
 * 判断字符串是否由数字组成
 * @param str 字符串
 * @return {Boolean}
 */
export function determineStrCombineByNum(str) {
  return !!str && (EMPLOYEE_NUM_REG.test(str) || NUMBER_REG.test(str))
}

/**
 * @description 手机号星号展示
 */
export const encodePhone = phone => {
  return phone ? phone.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2') : phone
}

// 判断空字符串
export const isStringEmpty = value => value === '' || value === 'null' || value === 'undefined'

// 判断是否是 android终端
export const isAndroidClient = () => {
  const u = navigator.userAgent
  return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 || /(Android)/i.test(u)
}

// 判断是否是 iOS终端
export const isIOSClient = () => {
  const u = navigator.userAgent
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || /(iPhone|iPad|iPod|iOS)/i.test(u)
}


/* 判断客户端 android ios */
export const judgeClient = () => {
  const isAndroid = isAndroidClient()
  const isIOS = isIOSClient()
  if (isAndroid) {
    return 'Android'
  } else if (isIOS) {
    return 'IOS'
  } else {
    return 'PC'
  }
}

export const getQueryVariable = (variable) => {
  const queryString = window.location.search.substring(1)
  const params = new URLSearchParams(queryString)
  return params.get(variable)
}


// 小数转换为百分数，解决js特殊小数乘以100的精度问题
export const convertPercent = (decimals) => {
  return decimals ? `${parseFloat((Number(decimals) * 100).toFixed(2))}%` : '0%'
}
